// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RobotPoseEstimationAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Navigation.Runtime.GroundTruthExtraction
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;

    using Microsoft.Robotics.IO;    
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Vision.Cameras;
    using Microsoft.Robotics.Vision.Cameras.Webcam;
    using Microsoft.Robotics.Vision.GroundTruthExtraction;
    using Microsoft.Robotics.Vision.Runtime.Cameras;    
    using Microsoft.Robotics.Vision.Runtime.GroundTruthExtraction;   
 
    /// <summary>
    /// Robot pose estimation agent which consumes a camera pose estimation message and publishes a robot pose estimation agent message using robot calibration info.
    /// This is useful to providing ground truth for metrics.
    /// </summary>
    [DataContract]
    public class RobotPoseEstimationAgent : ConsumerProducerAgent<CameraPoseEstimationAgentMessage, RobotPoseEstimationAgentMessage>
    {
        /// <summary>
        /// Calibration data export folder which contains robot calibration information.
        /// </summary>
        [DataMember(Name = "CalibrationDataExportFolder")]
        private readonly string calibrationDataExportFolder;

        /// <summary>
        /// Robot pose estimator.
        /// </summary>
        private RobotPoseEstimator robotPoseEstimator;

        /// <summary>
        /// Initializes a new instance of the RobotPoseEstimationAgent class.
        /// </summary>
        /// <param name="name">Agent name.</param>
        /// <param name="producer">Robot Pose Estimation Agent Message Producer.</param>  
        /// <param name="calibrationDataExportFolder">Calibration Data Export Folder</param>
        public RobotPoseEstimationAgent(
            string name,
            IProducer<CameraPoseEstimationAgentMessage> producer,
            string calibrationDataExportFolder)
            : base(name, producer.Name)
        {
            this.calibrationDataExportFolder = calibrationDataExportFolder;
        }

        /// <summary>
        /// Called when the agent is about to start running
        /// </summary>
        public unsafe override void OnActivated()
        {
            base.OnActivated();            
            this.robotPoseEstimator = new RobotPoseEstimator(this.calibrationDataExportFolder);
        }

        /// <summary>
        /// Called when the agent is about to end
        /// </summary>
        public override void OnDeactivated()
        {
            base.OnDeactivated();
        }

        /// <summary>
        /// Receive camera pose estimation message, generate and publish robot pose estimation message.
        /// </summary>
        /// <param name="message">Message to process</param>
        public override void Receive(CameraPoseEstimationAgentMessage message)
        {
            // Do not attempt to provide ground truth if the robot is not calibrated.
            if (!this.robotPoseEstimator.HasCalibrationInfo)
            {
                return;
            }

            Pose2D? globalPose = null;
            Pose2D? localPose = null;
            if (message.CameraPose != null)
            {
                if (message.Landmark != null)
                {
                    globalPose = this.robotPoseEstimator.EstimateRobotPose(
                        message.CameraPose.Value,
                        message.Landmark.Pose,
                        message.Landmark.TiltCalibrationParams,
                        message.Translations.Z);

                    localPose = new CoordinateTransform2D(message.Landmark.Pose).Reverse().Transform(globalPose.Value);
                }
                else
                {
                    globalPose = this.robotPoseEstimator.EstimateRobotPose(
                        message.CameraPose.Value,
                        new Pose2D(0, 0, 0),
                        new LandmarkTiltParams(0, 0),
                        message.Translations.Z);

                    localPose = globalPose;
                }
            }

            RobotPoseEstimationAgentMessage robotPoseMessage = new RobotPoseEstimationAgentMessage(
                message.OriginatingTime,
                globalPose,
                localPose,
                message.Landmark);

            this.Publisher.Post(robotPoseMessage);
        }
    }
}
